import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

export const asyncAdd = createAsyncThunk('asyncAdd',async(param) => {
  const r = await new Promise(reslove => {
    setTimeout(() => {
      reslove(param)
    }, 1000);
  })
  return r
})



export const cartSlice = createSlice({
  name: 'cart',
  initialState: {
    goodsCount: 0,
  },
  reducers: {
    addGoods: (state) => {
      // Redux Toolkit 允许我们在 reducers 中编写 mutating 逻辑。
      // 它实际上并没有 mutate state 因为它使用了 Immer 库，
      // 它检测到草稿 state 的变化并产生一个全新的基于这些更改的不可变 state
      state.goodsCount += 1;
    },
    minGoods: (state) => {
      state.goodsCount -= 1;
    },
    changeGoods: (state, action) => {
      console.log(action)
      state.goodsCount += action.payload
    }, 
  },
  extraReducers(builder) {
    builder.addCase(asyncAdd.fulfilled,(state,action) => {
      state.goodsCount += action.payload
    })
  }
});

// 为每个 case reducer 函数生成 Action creators
export const { addGoods, minGoods, changeGoods } = cartSlice.actions;

export default cartSlice.reducer;